package cn.darkhorse.device.service.impl;

import cn.darkhorse.common.constant.AuditTypeEnum;
import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.common.constant.WarnTypeEnum;
import cn.darkhorse.common.util.MsgUtil;
import cn.darkhorse.common.util.SysUserTranslation;
import cn.darkhorse.device.dto.MesRepairInfoDTO;
import cn.darkhorse.device.dto.MesReportDTO;
import cn.darkhorse.device.mapper.MesRepairInfoMapper;
import cn.darkhorse.device.pojo.MesDevice;
import cn.darkhorse.device.pojo.MesRepairEvaluateInfo;
import cn.darkhorse.device.pojo.MesRepairInfo;
import cn.darkhorse.device.pojo.MesSpareApplyRecords;
import cn.darkhorse.device.service.*;
import cn.darkhorse.device.vo.*;
import cn.darkhorse.messystem.vo.SysUserVO;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 维修单 服务实现类
 * </p>
 *
 * @author maoguanjun
 * @since 2022-11-11
 */
@Service
public class MesRepairInfoServiceImpl extends ServiceImpl<MesRepairInfoMapper, MesRepairInfo> implements MesRepairInfoService {
    @Resource
    private MesRepairInfoMapper mesRepairInfoMapper;
//    @Resource
//    private MesSpareApplyRecordsService mesSpareApplyRecordsService;
    @Resource
    private MesSparePartsService mesSparePartsService;
    @Resource
    private MesRepairEvaluateInfoService mesRepairEvaluateInfoService;
    @Resource
    private MesDeviceService mesDeviceService;
    @Resource
    private MesMsgAuditService mesMsgAuditService;
    @Resource
    private ISysDictTypeService dictTypeService;
    /**
     * 列表
     *
     * @param mesRepairInfoDTO
     * @return
     */
    @Override
    public List<MesRepairInfoVO> listAll(MesRepairInfoDTO mesRepairInfoDTO) {
        if(StringUtils.isBlank(mesRepairInfoDTO.getOrderType())){
            mesRepairInfoDTO.setOrderType(CommonConstant.ORDER_TYPE_DESC);
        }
        //return mesRepairInfoMapper.listAll(mesRepairInfoDTO);
        //TODO 10.17  派单、登记多人员
        List<MesRepairInfoVO> repairInfoVOS = mesRepairInfoMapper.listAll(mesRepairInfoDTO);
        if(repairInfoVOS.isEmpty()){
            return repairInfoVOS;
        }
        //TODO 翻译人员 10.17
        SysUserTranslation st = new SysUserTranslation();
        for(MesRepairInfoVO repairInfoVO:repairInfoVOS){
            //人员翻译
            repairInfoVO.setAssignedPersonNames(st.personnelTranslation(repairInfoVO.getAssignedPersons()));
            repairInfoVO.setMaintenancePersonNames(st.personnelTranslation(repairInfoVO.getMaintenancePersons()));
        }
        return repairInfoVOS;
    }


    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public MesRepairInfoVO view(Long id) {
        MesRepairInfo info=getById(id);
        if(null==info){
            throw new ServiceException("该业务单据已删除!");
        }
        //翻译多人员
        SysUserTranslation st = new SysUserTranslation();

        MesRepairInfoVO vo=new MesRepairInfoVO();
        BeanUtils.copyProperties(info,vo);
        MesDevice device=mesDeviceService.getById(info.getDeviceId());
        if(null!=device){
            vo.setHeader(device.getHeader());
        }
        LambdaQueryWrapper<MesRepairEvaluateInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesRepairEvaluateInfo::getRepairId,info.getId());
        MesRepairEvaluateInfo evaluateInfo=mesRepairEvaluateInfoService.getOne(wrapper);
        if(null!=evaluateInfo){
            vo.setLevel(evaluateInfo.getLevel());
        }
//        List<MesSpareApplyRecordsVO> list=mesSpareApplyRecordsService.listAll(null,null,id,CommonConstant.ORDER_TYPE_DESC);
//        if(null!=list&&list.size()>0){
//            vo.setMesSpareApplyRecordsVOList(list);
//        }
        //人员翻译
        vo.setAssignedPersonNames(st.personnelTranslation(vo.getAssignedPersons()));
        vo.setMaintenancePersonNames(st.personnelTranslation(vo.getMaintenancePersons()));
        return vo;
    }

    /**
     * 保存
     *
     * @param mesRepairInfo
     * @return
     */
    @Override
    public boolean saveMesRepairInfo(MesRepairInfo mesRepairInfo) {
        LambdaQueryWrapper<MesRepairInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesRepairInfo::getRepairNum,mesRepairInfo.getRepairNum());
        if(null!=mesRepairInfo.getId()){
            wrapper.ne(MesRepairInfo::getId,mesRepairInfo.getId());
        }
        Long count=count(wrapper);
        if(count>0){
            throw new ServiceException("同公司下维修单号不允许重复！");
        }
        boolean isInsert=false;
        if(null!=mesRepairInfo.getId()){
            MesRepairInfo info=getById(mesRepairInfo.getId());
            if(!CommonConstant.REPAIR_STATUS_WAIT_DISPATCH.equals(info.getRepairStatus())){
                throw new ServiceException("只有待派单的记录可以修改！");
            }
//            mesSpareApplyRecordsService.deleteByRepairId(mesRepairInfo.getId());
        }else{
            isInsert=true;
        }
        boolean b = saveOrUpdate(mesRepairInfo);

        //首次保存才发消息通知
        if(isInsert) {
            // 发送消息,到队列
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", WarnTypeEnum.REPAIRE.getTypeName());
            jsonObject.put("businessId", mesRepairInfo.getId());
            jsonObject.put("createTime", LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
            MsgUtil.sendWaringMsg(jsonObject.toJSONString());
        }

        return b;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        MesRepairInfo info=getById(id);
        if(!CommonConstant.REPAIR_STATUS_WAIT_DISPATCH.equals(info.getRepairStatus())){
            throw new ServiceException("只有待派单的记录可以删除！");
        }
//        mesSpareApplyRecordsService.deleteByRepairId(info.getId());
        //删除未审已删除消息
//        mesMsgAuditService.removeMsg(info.getId(),AuditTypeEnum.REPAIRE.getType());
        return  removeById(id);
    }

    /**
     * 派单
     *
     * @param receiver
     * @return
     */
    @Override
    public boolean dispatch(Long id,Long receiver) {
        MesRepairInfo info=getById(id);
        if(!CommonConstant.REPAIR_STATUS_WAIT_DISPATCH.equals(info.getRepairStatus())){
            throw new ServiceException("只有待派单的记录可以派单！");
        }
        info.setReceiver(receiver);
        info.setRepairStatus(CommonConstant.REPAIR_STATUS_WAIT_RECEIVE);

        // 发送消息,到队列
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", WarnTypeEnum.REPAIRE.getTypeName());
        jsonObject.put("businessId",info.getId());
        jsonObject.put("createTime", LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        MsgUtil.sendWaringMsg(jsonObject.toJSONString());

        return updateById(info);
    }

    @Override
    public boolean dispatch2(Long id,String userIds) {
        MesRepairInfo info=getById(id);
        if(!CommonConstant.REPAIR_STATUS_WAIT_DISPATCH.equals(info.getRepairStatus())){
            throw new ServiceException("只有待派单的记录可以派单！");
        }
        info.setAssignedPersons(userIds);
        info.setRepairStatus(CommonConstant.REPAIR_STATUS_WAIT_RECEIVE);

        // 发送消息,到队列
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", WarnTypeEnum.REPAIRE.getTypeName());
        jsonObject.put("businessId",info.getId());
        jsonObject.put("createTime", LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        MsgUtil.sendWaringMsg(jsonObject.toJSONString());

        return updateById(info);
    }



    @Override
    public boolean cancelDispatch(Long id) {
        MesRepairInfo info=getById(id);
        if(!CommonConstant.REPAIR_STATUS_WAIT_RECEIVE.equals(info.getRepairStatus())){
            throw new ServiceException("只有待接单的记录可以取消派单！");
        }
        //TODO 10.17 派单多选人员
        //info.setReceiver(null);
        info.setAssignedPersons(null);
        info.setRepairStatus(CommonConstant.REPAIR_STATUS_WAIT_DISPATCH);

        // 发送消息,到队列
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", WarnTypeEnum.REPAIRE.getTypeName());
        jsonObject.put("businessId",info.getId());
        jsonObject.put("createTime", LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        MsgUtil.sendWaringMsg(jsonObject.toJSONString());

        return updateById(info);
    }

    /**
     * 接单
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public boolean receive(Long id, Long userId) {
        MesRepairInfo info=getById(id);
        //不再判定接单人与单据是否一致，谁都可以接单
        /*if(null==info.getReceiver()||!userId.equals(info.getReceiver())){
            throw new ServiceException("接单人信息异常");
        }*/
        //TODO 10.17
        String assignedPersons = info.getAssignedPersons();
        if(StringUtils.isNotBlank(assignedPersons)){
            List<String> assList = Arrays.asList(assignedPersons.split(","));
            if(!assList.contains(userId.toString())){
                throw new ServiceException("指派其他人员，不能接单！");
            }
        }else {
            throw new ServiceException("未指派，不能接单！");
        }


        if(!CommonConstant.REPAIR_STATUS_WAIT_RECEIVE.equals(info.getRepairStatus())){
            throw new ServiceException("只有待接单的记录可以接单！");
        }
        info.setReceiver(userId);
        info.setReceiveDate(LocalDateTime.now());
        info.setRepairStatus(CommonConstant.REPAIR_STATUS_UNDER_REPAIR);
        return updateById(info);
    }

    /**
     *  登记
     * @param mesRepairInfoDTO
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean registration(MesRepairInfoDTO mesRepairInfoDTO) {
        MesRepairInfo info=getById(mesRepairInfoDTO.getId());
        if(null!=info){
            if(!CommonConstant.REPAIR_STATUS_UNDER_REPAIR.equals(info.getRepairStatus())&&!CommonConstant.REPAIR_STATUS_COMPLETE.equals(info.getRepairStatus())){
                throw new ServiceException("只有维修中和已完成的单据可以登记！");
            }
//            List<MesSpareApplyRecords> list = mesSpareApplyRecordsService.list(new LambdaQueryWrapper<MesSpareApplyRecords>()
//                    .eq(MesSpareApplyRecords::getRepairId, mesRepairInfoDTO.getId()));
//            if (null != list && list.size() > 0) {
//                list.forEach(item -> {
//                    if (CommonConstant.AUDIT_STATUS_REVIEWED.equals(item.getAuditStatus())) {
//                        throw new ServiceException("申请单已审核，请弃审后修改!");
//                    }
//                    if (CommonConstant.AUDIT_STATUS_UNDER_REVIEWED.equals(item.getAuditStatus())) {
//                        throw new ServiceException("备件申请单已提交，不可修改备件信息!");
//                    }
//                    mesSparePartsService.upInventory(item.getSpareId(), item.getApplyNum(), BigDecimal.ZERO, true,CommonConstant.SPARE_APPLY_TYPE_REPAIR);
//                    mesSpareApplyRecordsService.removeById(item.getId());
//                });
//            }
//            //申请备件
//            if(CommonConstant.APPLY_SPARE_STASUS.equals(mesRepairInfoDTO.getApplyStatus())) {
//                mesRepairInfoDTO.getMesSpareApplyRecordsList().forEach(item -> {
//                    item.setRepairId(mesRepairInfoDTO.getId());
//                    item.setApplyType(CommonConstant.SPARE_APPLY_TYPE_REPAIR);
//                    item.setAuditStatus(CommonConstant.AUDIT_STATUS_PENDING_TRIAL);
//                    item.setRepairNum(info.getRepairNum());
//                    item.setApplyPerson(mesRepairInfoDTO.getReceiveCreator());
//                    item.setApplyDept(info.getDept());
//                    item.setApplyTime(LocalDateTime.now());
//                    mesSparePartsService.upInventory(item.getSpareId(), item.getApplyNum(), BigDecimal.ZERO, false,CommonConstant.SPARE_APPLY_TYPE_REPAIR);
////                    mesSpareApplyRecordsService.save(item);
//                    //发送消息提醒
////                    mesSpareApplyRecordsService.sendWarnMsg(item.getSpareId(),item.getId(),item.getApplyNum());
//                });
//                //mesSpareApplyRecordsService.saveBatch(mesRepairInfoDTO.getMesSpareApplyRecordsList());
//            }
        }else {
            throw new ServiceException("维修单不存在！");
        }
        info.setMalfunctionType(mesRepairInfoDTO.getMalfunctionType());
        info.setMalfunctionTypeStr(mesRepairInfoDTO.getMalfunctionTypeStr());
        info.setMalfunctionDescription(mesRepairInfoDTO.getMalfunctionDescription());
        //20230818 增加故障图片
        info.setMalfunctionPic(mesRepairInfoDTO.getMalfunctionPic());
        info.setReceiveCreator(mesRepairInfoDTO.getReceiveCreator());
        info.setReviceCreatorDept(mesRepairInfoDTO.getReviceCreatorDept());
        info.setReceiveCreatorDate(mesRepairInfoDTO.getReceiveCreatorDate());
        info.setApplyStatus(mesRepairInfoDTO.getApplyStatus());
        info.setFinishDate(LocalDateTime.now());
        info.setRepairStatus(CommonConstant.REPAIR_STATUS_COMPLETE);
        info.setAttachments(mesRepairInfoDTO.getAttachments());
        info.setSpareUseInfo(mesRepairInfoDTO.getSpareUseInfo());
        info.setRepairMalfunctionDescription(mesRepairInfoDTO.getRepairMalfunctionDescription());
        info.setRepairMalfunctionTypeStr(mesRepairInfoDTO.getRepairMalfunctionTypeStr());
        info.setRepairProcessDescription(mesRepairInfoDTO.getRepairProcessDescription());
        //TODO 10.17 增加多维修人员
        info.setMaintenancePersons(mesRepairInfoDTO.getMaintenancePersons());
        return updateById(info);
    }

    /**
     * 评价
     *
     * @param id
     * @param level
     * @param content
     * @param userId
     * @return
     */
    @Override
    public boolean evaluate(Long id, Integer level, String content, Long userId) {
        MesRepairInfo info=getById(id);
        if(null!=info){
           LambdaQueryWrapper<MesRepairEvaluateInfo>  wrapper=new LambdaQueryWrapper<>();
           wrapper.eq(MesRepairEvaluateInfo::getRepairId,id);
            mesRepairEvaluateInfoService.remove(wrapper);
            MesRepairEvaluateInfo mesRepairEvaluateInfo=new MesRepairEvaluateInfo();
            mesRepairEvaluateInfo.setRepairId(info.getId());
            mesRepairEvaluateInfo.setCreator(userId);
            mesRepairEvaluateInfo.setRepairNum(info.getRepairNum());
            mesRepairEvaluateInfo.setContent(content);
            mesRepairEvaluateInfo.setLevel(level);
            mesRepairEvaluateInfo.setGmtCreate(LocalDateTime.now());
            return mesRepairEvaluateInfoService.save(mesRepairEvaluateInfo);
        }
        return false;
    }

    /**
     * 提交
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(Long id) {
        MesRepairInfo info=getById(id);
        if(null!=info){
//            LambdaQueryWrapper<MesSpareApplyRecords> wrapper=new LambdaQueryWrapper<>();
//            wrapper.eq(MesSpareApplyRecords::getRepairId, id);
//            wrapper.ne(MesSpareApplyRecords::getAuditStatus,CommonConstant.AUDIT_STATUS_REVIEWED);
//            Long count=mesSpareApplyRecordsService.count(wrapper);
//            if(count>0){
                //throw new ServiceException("存在未审核的备件申请记录，请先审核！");
//                throw new ServiceException("备件申请单未审核通过，不可提交！");
//            }
            info.setAuditStatus(CommonConstant.AUDIT_STATUS_UNDER_REVIEWED);
            //发送审核消息
            mesMsgAuditService.sendAuditMsg(AuditTypeEnum.REPAIRE.getTypeName(), info.getId(), null);
            return  updateById(info);
        }
        return false;
    }

    /**
     * 审核通过
     *
     * @param id
     * @param approver
     * @param approveTime
     * @param auditStatus
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(Long id, Long approver, String approveTime, Integer auditStatus) {
        MesRepairInfo info=getById(id);
        if(null!=info){
            if(auditStatus.equals(CommonConstant.AUDIT_STATUS_REVIEWED)){
                info.setApprover(approver);
                info.setApproveTime(LocalDateTime.parse(approveTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }else {
                info.setApprover(approver);
                info.setApproveTime(LocalDateTime.parse(approveTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            info.setAuditStatus(auditStatus);
            //更新审核通知
            mesMsgAuditService.upAuditMsg(id,approver,approveTime,auditStatus,AuditTypeEnum.REPAIRE.getType());
            return updateById(info);
        }
        return false;
    }

    /**
     * 弃审
     *
     * @param id
     * @return
     */
    @Override
    public boolean waiver(Long id) {
        MesRepairInfo info=getById(id);
        if(null!=info){
            info.setAuditStatus(CommonConstant.AUDIT_STATUS_PENDING_TRIAL);
            return updateById(info);
        }
        return false;
    }

    /**
     * 设备维修分析
     * @param repairReportDTO
     * @return
     */
    @Override
    public LineReportVO deviceAnalyse(MesReportDTO repairReportDTO) {
        LineReportVO res = new LineReportVO();
        setDateAndTypeParam(repairReportDTO);

        if (repairReportDTO.getType()!=null){
            List<MesDeviceRepairReportVO> repairReportVOS = null;
            if (repairReportDTO.getType().equals(2)){
                repairReportVOS = mesRepairInfoMapper.deviceAnalyseByDept(repairReportDTO);
            }else {
                repairReportVOS =  mesRepairInfoMapper.deviceAnalyse(repairReportDTO);
            }

            ArrayList<LineReportDataVO> dataVOS = new ArrayList<>();
            LineReportDataVO bar = new LineReportDataVO();
            LineReportDataVO line = new LineReportDataVO();

            bar.setName("故障次数");
            bar.setData(repairReportVOS.stream().map(MesDeviceRepairReportVO::getFaultNum).toArray());
            line.setName("维修用时");
            line.setData(repairReportVOS.stream().map(MesDeviceRepairReportVO::getRepairTimeSum).toArray());
            dataVOS.add(bar);
            dataVOS.add(line);

            res.setXCoordinate(repairReportVOS.stream().map(MesDeviceRepairReportVO::getName).toArray());
            res.setYCoordinate(dataVOS);
            res.setTableDataList(repairReportVOS);
        }
        return res;
    }

    /**
     * 故障类型分析饼图
     * @param repairReportDTO
     * @return
     */
    @Override
    public List<PieReportVO> faultTypeAnalysePie(MesReportDTO repairReportDTO) {
        setDateAndTypeParam(repairReportDTO);

        return mesRepairInfoMapper.faultTypeAnalysePie(repairReportDTO);
    }
    /**
     * 故障类型分析折线图
     * @param repairReportDTO
     * @return
     */
    @Override
    public LineReportVO faultTypeAnalyseLine(MesReportDTO repairReportDTO) {
        setDateAndTypeParam(repairReportDTO);
        LineReportVO lineReportVO = new LineReportVO();
        Integer type = repairReportDTO.getType();
//        构建图表数据
        List<PieReportVO> lineList = mesRepairInfoMapper.faultTypeAnalyseLineList(repairReportDTO);
//        获取列表数据, 过滤出X轴所需数组
        lineReportVO.setTableDataList(lineList);
        Object[] array = lineList.stream().map(PieReportVO::getName).toArray();
        lineReportVO.setXCoordinate(array);
//        构建Y轴数据
        ArrayList<LineReportDataVO> lineReportDataVOS = new ArrayList<>();
        // 每个字典值为一条折线
        List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType(type.equals(1) ? "fault_category" : "failure_level");
        for (SysDictData dictData : sysDictDataList) {
            LineReportDataVO dataVO = new LineReportDataVO();
            dataVO.setName(dictData.getDictLabel());
            Long[] values = new Long[array.length];
            // 给每条折线对应X轴的位置处赋值
            for (int i = 0; i < array.length; i++) {

                String s = String.valueOf(array[i]);
                LambdaQueryWrapper<MesRepairInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(MesRepairInfo::getDelFlag,0);
                if (type.equals(1)){
                    wrapper.eq(MesRepairInfo::getMalfunctionType,dictData.getDictValue());
                }else {
                    wrapper.eq(MesRepairInfo::getMalfunctionLevel,dictData.getDictValue());
                }
                if (repairReportDTO.getDept() != null){
                    wrapper.eq(MesRepairInfo::getDept, repairReportDTO.getDept());
                }
                if (repairReportDTO.getDeviceType() != null){
                    wrapper.eq(MesRepairInfo::getDeviceType, repairReportDTO.getDeviceType());
                }
                if (StringUtils.isNotEmpty((repairReportDTO.getDeviceName() ))) {
                    wrapper.like(MesRepairInfo::getDeviceName, repairReportDTO.getDeviceName());
                }
//                wrapper.between(MesRepairInfo::getGmtCraeate, repairReportDTO.getBeginDate(), repairReportDTO.getEndDate());
                wrapper.apply(" date_format(gmt_craeate,'%Y-%m-%d') = '"+s+"'");
                long count = count(wrapper);
                values[i] = count;
            }
            dataVO.setData(values);
            lineReportDataVOS.add(dataVO);
        }
        lineReportVO.setYCoordinate(lineReportDataVOS);
        return lineReportVO;
    }

    /**
     * 维修类型分析饼图
     * @param repairReportDTO
     * @return
     */
    @Override
    public List<PieReportVO> repairTypeAnalysePie(MesReportDTO repairReportDTO) {
        setDateAndTypeParam(repairReportDTO);

        return mesRepairInfoMapper.repairTypeAnalysePie(repairReportDTO);
    }


    /**
     * 维修类型分析折线图和表格
     * @param repairReportDTO
     * @return
     */
    @Override
    public LineReportVO repairTypeAnalyseLine(MesReportDTO repairReportDTO) {
        setDateAndTypeParam(repairReportDTO);

        LineReportVO lineReportVO = new LineReportVO();
        Integer type = repairReportDTO.getType();
//        构建图表数据
        List<PieReportVO> lineList = mesRepairInfoMapper.repairTypeAnalyseLineList(repairReportDTO);
//        获取列表数据, 过滤出X轴所需数组
        lineReportVO.setTableDataList(lineList);
        Object[] array = lineList.stream().map(PieReportVO::getName).toArray();
        lineReportVO.setXCoordinate(array);
//        构建Y轴数据
        ArrayList<LineReportDataVO> lineReportDataVOS = new ArrayList<>();
        // 每个字典值为一条折线
        List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType(type.equals(1) ? "repair_type" : "repair_level");
        for (SysDictData dictData : sysDictDataList) {
            LineReportDataVO dataVO = new LineReportDataVO();
            dataVO.setName(dictData.getDictLabel());
            Long[] values = new Long[array.length];
            // 给每条折线对应X轴的位置处赋值
            for (int i = 0; i < array.length; i++) {

                String s = String.valueOf(array[i]);
                LambdaQueryWrapper<MesRepairInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(MesRepairInfo::getDelFlag,0);
                if (type.equals(1)){

                    wrapper.eq(MesRepairInfo::getRepairType,dictData.getDictValue());
                }else {
                    wrapper.eq(MesRepairInfo::getRepairLevel,dictData.getDictValue());
                }
                if (repairReportDTO.getDept() != null){
                    wrapper.eq(MesRepairInfo::getDept, repairReportDTO.getDept());
                }
                if (repairReportDTO.getDeviceType() != null){
                    wrapper.eq(MesRepairInfo::getDeviceType, repairReportDTO.getDeviceType());
                }
                if (StringUtils.isNotEmpty((repairReportDTO.getDeviceName() ))) {
                    wrapper.like(MesRepairInfo::getDeviceName, repairReportDTO.getDeviceName());
                }
//                wrapper.between(MesRepairInfo::getGmtCraeate, repairReportDTO.getBeginDate(), repairReportDTO.getEndDate());
                wrapper.apply("date_format(gmt_craeate,'%Y-%m-%d') = '"+s+"'");
                long count = count(wrapper);
                values[i] = count;
            }
            dataVO.setData(values);
            lineReportDataVOS.add(dataVO);
        }
        lineReportVO.setYCoordinate(lineReportDataVOS);
        return lineReportVO;
    }

    @Override
    public LineReportVO MTTRLine(MesReportDTO repairReportDTO) {
        String year = repairReportDTO.getYear();
        LineReportVO lineReportVO = new LineReportVO();
//        构建X轴数据 12个月
        String[] array = new String[12];
        if (StringUtils.isNotEmpty(year)){
            for (int i = 0; i < 12; i++) {
                if (i+1 < 10){
                    array[i] = year+"-0"+(i+1);
                }else {
                    array[i] = year+"-"+(i+1);
                }
            }
        }else {
            for (int i = 0; i < 12; i++) {
                if (i+1 < 10){
                    array[i] = LocalDateTime.now().getYear()+"-0"+(i+1);
                }else {
                    array[i] = LocalDateTime.now().getYear()+"-"+(i+1);
                }
            }
        }

        lineReportVO.setXCoordinate(array);

        LambdaQueryWrapper<MesRepairInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MesRepairInfo::getDelFlag,0);
        wrapper.eq(MesRepairInfo::getAuditStatus,5);
        if (repairReportDTO.getDept() != null){
            wrapper.eq(MesRepairInfo::getDept, repairReportDTO.getDept());
        }
        if (repairReportDTO.getDeviceType() != null){
            wrapper.eq(MesRepairInfo::getDeviceType, repairReportDTO.getDeviceType());
        }
        wrapper.apply("date_format(gmt_craeate,'%Y') = '"+year+"'");
        List<MesRepairInfo> infoList = list(wrapper);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

//        使用流对 infoList 按照年月进行分组
        Map<String, List<MesRepairInfo>> groupedByMonth = infoList.stream()
                .collect(Collectors.groupingBy(
                        mesRepairInfo -> mesRepairInfo.getGmtCraeate().format(formatter)
                ));
        Double[] values = new Double[array.length];
        for (int i = 0; i < array.length; i++) {

            String month = array[i];




            List<MesRepairInfo> repairInfos = groupedByMonth.get(month);
            if (repairInfos != null) {
                BigDecimal totalHours = new BigDecimal(0);
                for (MesRepairInfo repairInfo : repairInfos) {
                    Integer repairHour = repairInfo.getRepairHour();
                    Integer repairMinute = repairInfo.getRepairMinute();
                    // 将分钟转换为小时并累加
                    BigDecimal hours =new BigDecimal( repairHour != null ? repairHour : 0);
                    BigDecimal minutes =new BigDecimal( repairMinute != null ? repairMinute : 0);
                    totalHours = totalHours.add(hours.add(minutes.divide(new BigDecimal(60),8, RoundingMode.HALF_UP)));
                }
                values[i] = totalHours.divide(new BigDecimal(repairInfos.size()), 1, RoundingMode.HALF_UP).doubleValue();
            }else {
                values[i] = 0.00;
            }
        }

        lineReportVO.setYCoordinate(Arrays.asList(values));
        return lineReportVO;
    }


    /**
     * 插入默认的参数
     * @param repairReportDTO
     * @return
     */
    public static void setDateAndTypeParam(MesReportDTO repairReportDTO) {
        LocalDate now = LocalDate.now();
        if (repairReportDTO.getDateType() == null && repairReportDTO.getBeginDate() == null && repairReportDTO.getEndDate() == null){
            repairReportDTO.setDateType(1);
        }
        if (repairReportDTO.getBeginDate() != null && repairReportDTO.getEndDate() != null){
            return;
        }
        if (repairReportDTO.getType()==null) {
            repairReportDTO.setType(1);
        }
        if (repairReportDTO.getDateType().equals(1)){
            // 本月
            LocalDate first = now.with(TemporalAdjusters.firstDayOfMonth());
            repairReportDTO.setBeginDate(first);
            LocalDate last = now.with(TemporalAdjusters.lastDayOfMonth());
            repairReportDTO.setEndDate(last);
        }else if (repairReportDTO.getDateType().equals(2)){
            // 上月
            LocalDate dateTime = now.plusMonths(-1);
            LocalDate first = dateTime.with(TemporalAdjusters.firstDayOfMonth());
            repairReportDTO.setBeginDate(first);
            LocalDate last = dateTime.with(TemporalAdjusters.lastDayOfMonth());
            repairReportDTO.setEndDate(last);
        }else if (repairReportDTO.getDateType().equals(3)){
            // 90天
            repairReportDTO.setBeginDate(now.plusDays(-90));
            repairReportDTO.setEndDate(now);
        }
    }

    /**
     * 查询班组人员状态
     *
     * @param list
     */
    @Override
    public void getUserStatus(List<SysUserVO> list) {
        //获取人员列表
        Set<Long> userIds = list.stream().map(SysUser::getUserId).collect(Collectors.toSet());
        List<SysUserVO> userVOS=mesRepairInfoMapper.getUserStatus(userIds);
        Map<Long, Integer> repairMap = userVOS.stream().collect(Collectors.toMap(SysUser::getUserId, SysUserVO::getRepairNum));
        list.forEach(item->{
            if(repairMap.containsKey(item.getUserId())){
                item.setRepaitStatus(1);
                item.setRepaitStatusName("维修中");
                item.setRepairNum(repairMap.get(item.getUserId()));
            }else{
                item.setRepaitStatus(0);
                item.setRepaitStatusName("空闲中");
                item.setRepairNum(0);
            }
        });
    }
}
